package desktop.core.playfield;

import pulpcore.Input;
import pulpcore.Stage;
import pulpcore.animation.Timeline;
import pulpcore.animation.event.AddSpriteEvent;
import pulpcore.animation.event.RemoveSpriteEvent;
import pulpcore.scene.Scene2D;
import pulpcore.sprite.ImageSprite;
import desktop.core.bar.Bar;
import desktop.core.bar.BarController;
import desktop.playerguide.GameOverScene;

public class PlayFieldViewSingleBar extends PlayFieldViewAbstract {

	private Bar currentBar;
	private Bar nextBar;
	private BarController barController;

	public PlayFieldViewSingleBar(double x, double y, double width,
			double height, PlayFieldModel playFieldModel,
			BarController barController) {
		this(x, y, width, height, playFieldModel, barController,
				"PlayingField.jpg");
	}

	public PlayFieldViewSingleBar(double x, double y, double width,
			double height, PlayFieldModel playFieldModel,
			BarController barController, String background) {
		super(x, y, width, height, playFieldModel);

		add(new ImageSprite(background, 0, 0, this.width.get(), this.height
				.get()));

		this.currentBar = this.receiveNextBar(0);

		timeline = new Timeline();
		timeline.add(new AddSpriteEvent(this, currentBar, 0));
		((Scene2D) Stage.getScene()).addTimeline(timeline);

		timeline = new Timeline();
		timeline.add(new AddSpriteEvent(this, currentBar, 0));
		replay.addTimeline(timeline);

		this.nextBar = this.receiveNextBar(0);
		this.barController = barController;
	}

	public Bar getNextBar() {
		return this.nextBar;
	}

	private void play(int elapsedTime) {

		controlSpeed(elapsedTime);

		try {
			if (this.reachesBottom(this.currentBar)) {
				this.applySquaresFromBar(this.currentBar);
				this.timeToControlBar += this.applySquareElimination();

				timeline = new Timeline();
				timeline.add(new RemoveSpriteEvent(this, currentBar, 0));
				timeline.add(new AddSpriteEvent(this, nextBar, 0));
				((Scene2D) Stage.getScene()).addTimeline(timeline);

				timeline = new Timeline();
				timeline.add(new RemoveSpriteEvent(this, currentBar, 0));
				timeline.add(new AddSpriteEvent(this, nextBar, 0));
				replay.addTimeline(timeline);

				this.currentBar = this.nextBar;
				this.nextBar = this.receiveNextBar(0);
			}
			controlCurrentBar(currentBar, barController, elapsedTime);
		} catch (ArrayIndexOutOfBoundsException e) {
			Stage.pushScene(new GameOverScene(getPointsTotally()));
		}
	}

	@Override
	public void update(int elapsedTime) {

		if (Input.isPressed(Input.KEY_ENTER) && (!replaying)) {
			replaying = true;
			((Scene2D) Stage.getScene()).removeAllTimelines(false);
			replay.replay();
		} else {
			play(elapsedTime);
		}

	}

	protected boolean canMoveLeft(Bar bar) {
		return (!this.isLeftEdge(bar)) && (!this.isLeftIntersecs(bar));
	}

	protected boolean canMoveRight(Bar bar) {
		return (!this.isRightEdge(bar)) && (!this.isRightIntersecs(bar));
	}

}